//
//  SYDownloadWorking.m
//  wuyeyu
//
//  Created by shuyang on 2018/11/6.
//  Copyright © 2018年 wuyewl. All rights reserved.
//

#import "SYDownloadWorking.h"

@interface SYDownloadWorking()<NSURLSessionDelegate>

@property (nonatomic, copy) NSString *requestURL;
@property (nonatomic, copy) NSString *fileName;
@property (nonatomic, strong) NSURLSessionDataTask *downloadTask;
@property(nonatomic,strong) NSMutableData *data;
/**总长度*/
@property(nonatomic,assign)NSInteger totalLength;

@end

@implementation SYDownloadWorking


- (instancetype)initDownloadFileWithFileUrl:(NSString*)requestURL fileName:(NSString *)fileName {
    if (self == [super init]) {
        self.fileName = fileName;
        self.requestURL = requestURL;
        self.totalLength = 1;
        
        if (self.downloadTask) {
            self.downloadTask = nil;
        }
        
        NSURL *url = [NSURL URLWithString:self.requestURL];
        //创建管理类NSURLSessionConfiguration
        NSURLSessionConfiguration *config =[NSURLSessionConfiguration defaultSessionConfiguration];
        config.HTTPAdditionalHeaders =@{@"Accept-Encoding":@""};

        //初始化session并制定代理
        NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
        
        self.downloadTask = [session dataTaskWithURL:url];
        // 开始
        [self.downloadTask resume];
    }
    return self;
}

// 下载暂停
- (void)downLoadPause
{
    [self.downloadTask suspend];
}
// 下载继续
- (void)downLoadResume
{
    [self.downloadTask resume];
    [self.downloadTask cancel];

}
// 关闭下载
- (void)downLoadCancel
{
    [self.downloadTask cancel];
}

#pragma mark ====  下载用到的 代理方法
#pragma mark *下载完成调用
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.completeBlock) {
            if (error) {
                self.completeBlock([NSData data], error);
            }else{
                self.completeBlock([NSData dataWithData:self.data], error);
            }
        }
    });
}


#pragma mark  ====  接收到数据调用
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler{
    //允许继续响应
    completionHandler(NSURLSessionResponseAllow);
    //获取文件的总大小
    self.totalLength = response.expectedContentLength;
}


#pragma mark  ===== 接收到数据调用
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data{
    //将每次接受到的数据拼接起来
    [self.data appendData:data];
    //计算当前下载的长度
    NSInteger nowlength = self.data.length;
    
    double progress = nowlength / self.totalLength;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.progressBlock) {
            self.progressBlock(progress, nowlength, self.totalLength);
        }
    });
}

+ (NSString *)getLocalFilePathWithFileName:(NSString *)fileName
{
    NSString * path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString *pathstring = [path stringByAppendingPathComponent:fileName];
    return pathstring;
}

//根据文件名判断是否已经保存到本地了
+ (BOOL)isSavedFileToLocalWithFileName:(NSString *)fileName {
    // 判断是否已经离线下载了
    NSString *path = [self getLocalFilePathWithFileName:fileName];
    NSFileManager *filemanager = [NSFileManager defaultManager];
    if ([filemanager fileExistsAtPath:path]) {
        return YES;
    }
    return NO;
}

+ (BOOL)savedFileToLocalWithFileName:(NSString *)fileName data:(NSData *)data {
    NSString *path = [self getLocalFilePathWithFileName:fileName];
    //将下载的二进制文件转成入文件
    NSFileManager *manager = [NSFileManager defaultManager];
    BOOL isDownLoad =  [manager createFileAtPath:path contents:data attributes:nil];
    if (isDownLoad) {
        return YES;
    }else{
        return NO;
    }
}

+ (BOOL)deleteFileName:(NSString *)fileName {

    NSString *path = [self getLocalFilePathWithFileName:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isSuccess = [fileManager removeItemAtPath:path error:nil];
    if (isSuccess) {
        return YES;
    }else{
        return NO;
    }
}

//懒加载
-(NSMutableData *)data{
    if (_data == nil) {
        _data = [NSMutableData data];
    }
    return _data;
}


@end
